package com.smallsoft.phongtucvietnam;

import java.util.ArrayList;

import com.smallsoft.adapter.ContentAdapter;
import com.smallsoft.beans.Content;
import com.smallsoft.helper.DatabaseHelper;
import com.smallsoft14.phongtucvietnam.R;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class ContentFragment extends Fragment{

	ViewGroup viewGroup;
	ListView listView;
	ArrayList<Content> contents = new ArrayList<Content>();
	DatabaseHelper dbHelper;
	ContentAdapter adapter;
	int catId;
	int position;
	String catName;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		catId = getArguments().getInt("catId");
		catName = getArguments().getString("name");
		position = getArguments().getInt("position");
		dbHelper = new DatabaseHelper(getActivity());
		contents = dbHelper.getContent(getActivity(), catId);
		adapter = new ContentAdapter(getActivity(), contents, position);
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if (viewGroup == null){
			viewGroup = (ViewGroup)inflater.inflate(R.layout.list_content, container, false);
			listView = (ListView)viewGroup.findViewById(R.id.list_view);
			listView.setAdapter(adapter);
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> adapterView, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					Bundle bundle = new Bundle();
					bundle.putString("catName", catName);
					bundle.putString("title", contents.get(position).getTitle());
					bundle.putString("content", contents.get(position).getContent());
					DetailFragment detail = new DetailFragment();
					detail.setArguments(bundle);
					FragmentTransaction trans = ContentFragment.this.getFragmentManager().beginTransaction();
					trans.replace(R.id.content_frame, detail);
					trans.addToBackStack(null);
					trans.commit();
				}
			});
		}else{
			((ViewGroup)this.viewGroup.getParent()).removeView(this.viewGroup);
		}
		return viewGroup;
	}
}
